# -*- coding: utf-8 -*-
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import json
import os
import subprocess
import sys
from datetime import datetime
from PIL import Image, ImageTk, ImageDraw  # 添加ImageDraw支持
import requests
from io import BytesIO
from concurrent.futures import ThreadPoolExecutor  # 添加线程池支持

# 导入路径工具
from path_utils import get_base_dir, get_config_path, get_game_path, get_asset_path, normalize_path, get_python_command


def get_game_icon(game_id):
    """获取游戏图标"""
    icons = {
        'tetris': '🧩',
        'snake': '🐍',
        'puzzle': '🧩',
        'memory': '🧠',
        'default': '🎮'
    }
    return icons.get(game_id, icons['default'])


# 全局变量定义
status_text = {'available': '可用', 'coming_soon': '即将推出', 'maintenance': '维护中'}


def should_show_game(game):
    """判断是否应该显示游戏"""
    return True  # 总是显示所有游戏


def get_setting_options(setting_key):
    """获取设置项的选项"""
    options = {
        'difficulty': ['easy', 'normal', 'hard', 'expert'],
        'theme': ['classic', 'modern', 'neon', 'retro'],
        'speed': ['slow', 'medium', 'fast', 'ultra'],
        'size': ['small', 'medium', 'large', '3x3', '4x4', '5x5']
    }
    return options.get(setting_key, [])


def create_setting_widget(parent, key, value, setting_vars):
    """创建设置项控件"""
    frame = tk.Frame(parent, bg='#2d2d2d')
    frame.pack(fill='x', padx=10, pady=5)

    label = tk.Label(frame, text=key.replace('_', ' ').title() + ':',
                     bg='#2d2d2d', fg='#ffffff',
                     font=('Arial', 11))
    label.pack(anchor='w')

    if isinstance(value, bool):
        var = tk.BooleanVar(value=value)
        checkbox = tk.Checkbutton(frame, text="启用", variable=var,
                                  bg='#2d2d2d', fg='#ffffff',
                                  selectcolor='#1e88e5',
                                  activebackground='#2d2d2d')
        checkbox.pack(anchor='w')
        setting_vars[key] = var

    elif isinstance(value, str):
        var = tk.StringVar(value=value)
        if key in ['difficulty', 'theme', 'speed', 'size']:
            options = get_setting_options(key)
            combo = ttk.Combobox(frame, textvariable=var, values=options, state='readonly')
            combo.pack(anchor='w', fill='x', pady=2)
        else:
            entry = tk.Entry(frame, textvariable=var, bg='#3d3d3d', fg='#ffffff',
                             insertbackground='#ffffff')
            entry.pack(anchor='w', fill='x', pady=2)
        setting_vars[key] = var

    elif isinstance(value, (int, float)):
        var = tk.StringVar(value=str(value))
        entry = tk.Entry(frame, textvariable=var, bg='#3d3d3d', fg='#ffffff',
                         insertbackground='#ffffff')
        entry.pack(anchor='w', fill='x', pady=2)
        setting_vars[key] = var


def setup_styles():
    """设置ttk样式"""
    style = ttk.Style()
    style.theme_use('clam')

    # 配置亮色主题样式
    style.configure('Title.TLabel',
                    background='#f8f9fa',
                    foreground='#2c3e50',
                    font=('Microsoft YaHei UI', 28, 'bold'),
                    padding=10)

    style.configure('GameCard.TFrame',
                    background='#ffffff',
                    relief='solid',
                    borderwidth=1)

    style.configure('GameCardHover.TFrame',
                    background='#f0f8ff',
                    relief='solid',
                    borderwidth=2)

    style.configure('GameTitle.TLabel',
                    background='#ffffff',
                    foreground='#2c3e50',
                    font=('Microsoft YaHei UI', 16, 'bold'))

    style.configure('GameDesc.TLabel',
                    background='#ffffff',
                    foreground='#6c757d',
                    font=('Microsoft YaHei UI', 10))

    style.configure('Action.TButton',
                    font=('Microsoft YaHei UI', 10, 'bold'),
                    padding=(12, 8),
                    relief='flat')

    style.map('Action.TButton',
              background=[('active', '#0056b3'), ('!active', '#007bff')],
              foreground=[('active', '#ffffff'), ('!active', '#ffffff')],
              relief=[('pressed', 'sunken'), ('!pressed', 'flat')])

    # 添加新的按钮样式
    style.configure('Success.TButton',
                    font=('Microsoft YaHei UI', 10, 'bold'),
                    padding=(12, 8),
                    relief='flat')

    style.map('Success.TButton',
              background=[('active', '#218838'), ('!active', '#28a745')],
              foreground=[('active', '#ffffff'), ('!active', '#ffffff')])

    style.configure('Secondary.TButton',
                    font=('Microsoft YaHei UI', 10, 'bold'),
                    padding=(12, 8),
                    relief='flat')

    style.map('Secondary.TButton',
              background=[('active', '#5a6268'), ('!active', '#6c757d')],
              foreground=[('active', '#ffffff'), ('!active', '#ffffff')])


class GameCollectionApp:
    def __init__(self, root):
        self.scrollable_frame = None
        self.root = root
        self.root.title("游戏集合中心")
        self.root.geometry("1200x800")  # 更大的窗口尺寸
        self.root.configure(bg='#f8f9fa')  # 亮色背景

        # 设置样式
        setup_styles()

        # 游戏配置文件 - 使用路径工具获取正确的路径
        self.config_file = get_config_path("games_config.json")
        self.games_data = self.load_games_config()

        # 缓存游戏图标和加载状态
        self.image_cache = {}
        self.image_loading = {}
        self.image_failed = set()

        # 使用线程池异步预加载图片
        self.executor = ThreadPoolExecutor(max_workers=4)
        self.preload_images_async()

        # 创建主界面
        self.create_main_interface()

        # 立即加载游戏列表
        self.refresh_games_list()

        # 绑定窗口关闭事件
        self.root.protocol("WM_DELETE_WINDOW", self.on_closing)

    def create_main_interface(self):
        """创建主界面"""
        # 标题栏 (减小高度)
        title_frame = tk.Frame(self.root, bg='#f8f9fa')
        title_frame.pack(fill='x', padx=30, pady=(15, 10))  # 减小垂直内边距

        title_label = ttk.Label(title_frame, text="🎮 游戏集合中心", style='Title.TLabel')
        title_label.pack(side='left')

        # 添加副标题 (减小字体)
        subtitle_label = tk.Label(title_frame, text="发现并享受精彩游戏",
                                 bg='#f8f9fa', fg='#6c757d',
                                 font=('Microsoft YaHei UI', 10))  # 字体从12减小到10
        subtitle_label.pack(side='left', padx=(10, 0))  # 减小水平内边距

        # 工具栏 (减小高度)
        toolbar_frame = tk.Frame(self.root, bg='#ffffff', relief='solid', bd=1)
        toolbar_frame.pack(fill='x', padx=30, pady=(0, 10))  # 减小底部内边距

        # 工具栏内容框架 (减小内边距)
        toolbar_content = tk.Frame(toolbar_frame, bg='#ffffff')
        toolbar_content.pack(fill='x', padx=10, pady=8)  # 减小内边距

        # 左侧按钮组
        left_buttons = tk.Frame(toolbar_content, bg='#ffffff')
        left_buttons.pack(side='left')

        ttk.Button(left_buttons, text="➕ 添加游戏", style='Success.TButton', command=self.add_game).pack(side='left', padx=(0, 10))
        ttk.Button(left_buttons, text="🔄 刷新列表", style='Action.TButton', command=self.refresh_games_list).pack(side='left', padx=(0, 10))
        ttk.Button(left_buttons, text="📊 游戏统计", style='Secondary.TButton', command=self.show_statistics).pack(side='left')

        # 右侧按钮组已移除以提高UI简洁度

        # 主内容区域
        main_frame = tk.Frame(self.root, bg='#f8f9fa')
        main_frame.pack(fill='both', expand=True, padx=30, pady=(0, 30))

        # 创建滚动区域
        self.create_scrollable_area(main_frame)

    def on_mousewheel(self, event):
        """处理鼠标滚动事件"""
        self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
        
    def create_scrollable_area(self, parent):
        """创建可滚动的游戏列表区域"""
        canvas = tk.Canvas(parent, bg='#f8f9fa', highlightthickness=0)
        scrollbar = ttk.Scrollbar(parent, orient="vertical", command=canvas.yview)
        self.scrollable_frame = tk.Frame(canvas, bg='#f8f9fa')

        self.scrollable_frame.bind(
            "<Configure>",
            lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
        )

        canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
        canvas.configure(yscrollcommand=scrollbar.set)

        canvas.bind("<MouseWheel>", self.on_mousewheel)
        # 将滚动事件也绑定到可滚动框架
        self.scrollable_frame.bind("<MouseWheel>", self.on_mousewheel)

        canvas.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")

        self.canvas = canvas

    def load_games_config(self):
        """加载游戏配置"""
        # 首先尝试加载配置文件
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    games = json.load(f)
                    if games and len(games) > 0:
                        return games
            except Exception as e:
                print(f"加载配置文件失败: {e}")
        
        # 如果配置文件不存在或为空，返回空列表
        # 这样会显示"暂无游戏"，而不是硬编码的默认游戏
        return []

    def save_games_config(self, games_data=None):
        """保存游戏配置"""
        if games_data is None:
            games_data = self.games_data

        with open(self.config_file, 'w', encoding='utf-8') as f:
            json.dump(games_data, f, ensure_ascii=False, indent=2)

    def preload_images_async(self):
        """异步预加载游戏图片"""
        def load_image_task(image_path):
            try:
                # 只处理本地文件路径
                if image_path and not image_path.startswith('http'):
                    try:
                        # 检查文件是否存在
                        if os.path.exists(image_path):
                            image = Image.open(image_path)
                            image = image.resize((220, 120), Image.LANCZOS)
                            return ImageTk.PhotoImage(image)
                    except Exception as e:
                        print(f"加载本地图片失败: {e}")
                return None
            except Exception as e:
                print(f"异步加载图片失败: {e}")
                return None
        
        # 提交所有图片加载任务
        futures = {}
        for game in self.games_data:
            image_path = game.get('image', '')
            # 只处理本地文件路径
            if image_path and not image_path.startswith('http') and image_path not in self.image_cache and image_path not in self.image_loading:
                self.image_loading[image_path] = True
                future = self.executor.submit(load_image_task, image_path)
                futures[future] = image_path
        
        # 处理完成的任务
        for future in futures:
            image_path = futures[future]
            try:
                photo = future.result()
                if photo:
                    self.image_cache[image_path] = photo
            except Exception as e:
                print(f"处理图片结果失败: {e}")
                self.image_failed.add(image_path)
            finally:
                if image_path in self.image_loading:
                    del self.image_loading[image_path]
                    
    def load_image(self, path, size=(220, 120)):
        """加载并缓存游戏图片"""
        # 如果是网络链接，使用默认占位符
        if path.startswith('http'):
            # 创建占位符图片
            placeholder = Image.new('RGB', size, (233, 236, 239))
            draw = ImageDraw.Draw(placeholder)
            draw.rectangle([0, 0, size[0]-1, size[1]-1], outline=(108, 117, 125), width=1)
            return ImageTk.PhotoImage(placeholder)
        
        # 获取完整的资源路径
        full_path = get_asset_path(path)
            
        # 检查本地路径
        if full_path in self.image_cache:
            return self.image_cache[full_path]
        
        # 如果图片正在加载中或加载失败，返回占位符
        if full_path in self.image_loading or full_path in self.image_failed:
            # 创建占位符图片
            placeholder = Image.new('RGB', size, (233, 236, 239))
            draw = ImageDraw.Draw(placeholder)
            draw.rectangle([0, 0, size[0]-1, size[1]-1], outline=(108, 117, 125), width=1)
            return ImageTk.PhotoImage(placeholder)
            
        # 尝试直接加载图片
        if os.path.exists(full_path):
            try:
                image = Image.open(full_path)
                image = image.resize(size, Image.LANCZOS)
                photo = ImageTk.PhotoImage(image)
                self.image_cache[full_path] = photo
                return photo
            except Exception as e:
                print(f"加载图片失败: {full_path}, 错误: {e}")
                self.image_failed.add(full_path)
        else:
            self.image_failed.add(full_path)
            
        # 启动异步加载
        self.preload_images_async()
        
        # 返回临时占位符
        placeholder = Image.new('RGB', size, (233, 236, 239))
        draw = ImageDraw.Draw(placeholder)
        draw.rectangle([0, 0, size[0]-1, size[1]-1], outline=(108, 117, 125), width=1)
        return ImageTk.PhotoImage(placeholder)

    def refresh_games_list(self):
        """刷新游戏列表"""
        for widget in self.scrollable_frame.winfo_children():
            widget.destroy()

        categories = {}
        for game in self.games_data:
            category = game.get('category', '其他')
            if category not in categories:
                categories[category] = []
            categories[category].append(game)

        row = 0
        for category, games in categories.items():
            category_frame = tk.Frame(self.scrollable_frame, bg='#f8f9fa')
            category_frame.grid(row=row, column=0, columnspan=3, sticky='ew', pady=(25, 15))

            category_label = tk.Label(category_frame,
                                      text=f"📁 {category}",
                                      bg='#f8f9fa',
                                      fg='#007bff',
                                      font=('Microsoft YaHei UI', 20, 'bold'))
            category_label.pack(anchor='w')

            # 添加分类描述
            category_count = len([g for g in games if should_show_game(g)])
            if category_count > 0:
                desc_label = tk.Label(category_frame,
                                     text=f"{category_count} 个游戏",
                                     bg='#f8f9fa',
                                     fg='#6c757d',
                                     font=('Microsoft YaHei UI', 11))
                desc_label.pack(anchor='w', padx=(30, 0))

            row += 1

            col = 0
            for game in games:
                if should_show_game(game):
                    self.create_game_card(game, row, col)
                    col += 1
                    if col >= 3:  # 3 cards per row for better spacing
                        col = 0
                        row += 1

            if col > 0:
                row += 1

        self.scrollable_frame.grid_columnconfigure((0, 1, 2), weight=1)

    def create_game_card(self, game, row, col):
        """创建游戏卡片"""
        card_frame = ttk.Frame(self.scrollable_frame, style='GameCard.TFrame')
        card_frame.grid(row=row, column=col, padx=15, pady=15, sticky='nsew')

        # 绑定滚动事件到整个卡片
        card_frame.bind("<MouseWheel>", self.on_mousewheel)
        
        # 添加悬停效果
        card_frame.bind("<Enter>", lambda e: card_frame.configure(style='GameCardHover.TFrame'))
        card_frame.bind("<Leave>", lambda e: card_frame.configure(style='GameCard.TFrame'))
        
        # 绑定滚动事件到卡片内的所有控件
        def bind_children(widget):
            for child in widget.winfo_children():
                child.bind("<MouseWheel>", self.on_mousewheel)
                bind_children(child)
        
        bind_children(card_frame)

        # 图片框架
        image_frame = tk.Frame(card_frame, bg='#ffffff')
        image_frame.pack(fill='x', padx=15, pady=(15, 10))

        # 加载游戏图片
        image_path = game.get('image', '')
        game_image = None
        
        if image_path:
            game_image = self.load_image(image_path, size=(280, 160))
        
        image_label = tk.Label(image_frame, bg='#ffffff')
        image_label.pack(fill='x')
        
        # 设置图片或图标
        if game_image:
            image_label.configure(image=game_image)
            image_label.image = game_image  # 保持引用
            
            # 如果图片之前未加载完成，添加延迟检查
            if image_path in self.image_loading and not image_path in self.image_cache:
                def check_image_loaded():
                    if image_path in self.image_cache:
                        # 图片已加载完成，更新显示
                        final_image = self.image_cache[image_path]
                        image_label.configure(image=final_image)
                        image_label.image = final_image
                    elif image_path in self.image_loading:
                        # 继续等待
                        self.root.after(500, check_image_loaded)
                
                self.root.after(500, check_image_loaded)
        else:
            # 显示游戏图标
            icon_label = tk.Label(image_frame, text=get_game_icon(game['id']),
                                  bg='#f8f9fa', fg='#007bff',
                                  font=('Microsoft YaHei UI', 48))
            icon_label.pack(fill='x', pady=30)

        # 状态标签，使用现代样式
        status_colors = {'available': '#28a745', 'coming_soon': '#ffc107', 'maintenance': '#dc3545'}
        status_text = {'available': '可用', 'coming_soon': '即将推出', 'maintenance': '维护中'}

        status_label = tk.Label(image_frame,
                                text=status_text.get(game['status'], '未知'),
                                bg=status_colors.get(game['status'], '#6c757d'),
                                fg='white',
                                font=('Microsoft YaHei UI', 9, 'bold'),
                                padx=10, pady=5,
                                relief='flat')
        status_label.place(relx=1.0, rely=0.0, anchor='ne', x=-10, y=10)

        # 信息框架
        info_frame = tk.Frame(card_frame, bg='#ffffff')
        info_frame.pack(fill='both', expand=True, padx=15, pady=(0, 10))

        # 游戏标题
        name_label = ttk.Label(info_frame, text=game['name'], style='GameTitle.TLabel')
        name_label.pack(anchor='w', pady=(8, 5))

        # 游戏描述
        desc_label = ttk.Label(info_frame, text=game['description'], style='GameDesc.TLabel',
                               wraplength=280, justify='left')
        desc_label.pack(anchor='w', pady=(0, 8))

        # 统计数据，使用现代图标
        stats_frame = tk.Frame(info_frame, bg='#ffffff')
        stats_frame.pack(fill='x', pady=(5, 10))

        rating_label = tk.Label(stats_frame, text=f"⭐ {game['rating']}",
                                bg='#ffffff', fg='#ffc107',
                                font=('Microsoft YaHei UI', 10, 'bold'))
        rating_label.pack(side='left')

        play_count_label = tk.Label(stats_frame, text=f"🎮 {game['play_count']}",
                                    bg='#ffffff', fg='#6c757d',
                                    font=('Microsoft YaHei UI', 10))
        play_count_label.pack(side='right')

        # 按钮框架，更好的间距
        button_frame = tk.Frame(card_frame, bg='#ffffff')
        button_frame.pack(fill='x', padx=15, pady=(0, 15))

        # 检查游戏文件是否存在
        game_path = get_game_path(game['path'])
        game_file_exists = os.path.exists(game_path)
        
        if game['status'] == 'available' and game_file_exists:
            play_btn = ttk.Button(button_frame, text="▶ 开始游戏", style='Success.TButton',
                                  command=lambda g=game: self.start_game(g))
            play_btn.pack(side='left', padx=(0, 8))
        elif not game_file_exists:
            # 文件不存在时显示警告按钮
            warning_btn = ttk.Button(button_frame, text="⚠ 文件缺失", style='Secondary.TButton',
                                    state='disabled')
            warning_btn.pack(side='left', padx=(0, 8))

        config_btn = ttk.Button(button_frame, text="⚙ 配置", style='Secondary.TButton',
                                command=lambda g=game: self.configure_game(g))
        config_btn.pack(side='left', padx=(0, 8))

        detail_btn = ttk.Button(button_frame, text="📋 详情", style='Action.TButton',
                                command=lambda g=game: self.show_game_details(g))
        detail_btn.pack(side='right')

    def start_game(self, game):
        """启动游戏"""
        # 使用路径工具获取完整的游戏路径
        game_path = get_game_path(game['path'])
            
        if not os.path.exists(game_path):
            messagebox.showerror("错误", f"游戏文件不存在！\n路径: {game_path}")
            return

        try:
            game['play_count'] += 1
            game['last_played'] = datetime.now().isoformat()
            self.save_games_config()

            if game_path.endswith('.py'):
                python_cmd = get_python_command()
                game_dir = os.path.dirname(game_path)
                subprocess.Popen([python_cmd, game_path], cwd=game_dir)
            else:
                subprocess.Popen([game_path], cwd=os.path.dirname(game_path))

            self.show_auto_close_message("启动成功", f"游戏 {game['name']} 已启动！", 3000)

        except Exception as e:
            messagebox.showerror("启动失败", f"无法启动游戏: {str(e)}")

    def show_auto_close_message(self, title, message, delay_ms=3000):
        """显示自动关闭的消息提示框"""
        # 创建自定义提示窗口
        msg_window = tk.Toplevel(self.root)
        msg_window.title(title)
        msg_window.geometry("400x150")
        msg_window.configure(bg='#2d2d2d')
        msg_window.resizable(False, False)
        
        # 设置窗口位置居中
        msg_window.transient(self.root)
        msg_window.grab_set()
        
        # 计算居中位置
        x = (msg_window.winfo_screenwidth() // 2) - (400 // 2)
        y = (msg_window.winfo_screenheight() // 2) - (150 // 2)
        msg_window.geometry(f"400x150+{x}+{y}")
        
        # 创建内容框架
        content_frame = tk.Frame(msg_window, bg='#2d2d2d')
        content_frame.pack(fill='both', expand=True, padx=20, pady=20)
        
        # 成功图标
        icon_label = tk.Label(content_frame, text="✅", 
                             bg='#2d2d2d', fg='#2ecc71',
                             font=('Arial', 24))
        icon_label.pack(pady=(0, 10))
        
        # 消息文本
        msg_label = tk.Label(content_frame, text=message,
                            bg='#2d2d2d', fg='#ffffff',
                            font=('Arial', 12),
                            wraplength=350, justify='center')
        msg_label.pack(pady=(0, 10))
        
        # 倒计时标签
        countdown_label = tk.Label(content_frame, text=f"({delay_ms//1000}秒后自动关闭)",
                                  bg='#2d2d2d', fg='#b3b3b3',
                                  font=('Arial', 10))
        countdown_label.pack()
        
        # 倒计时功能
        remaining_time = delay_ms // 1000
        
        def update_countdown():
            nonlocal remaining_time
            if remaining_time > 0:
                countdown_label.config(text=f"({remaining_time}秒后自动关闭)")
                remaining_time -= 1
                msg_window.after(1000, update_countdown)
            else:
                msg_window.destroy()
        
        # 立即关闭按钮
        close_btn = tk.Button(content_frame, text="立即关闭",
                             bg='#1565c0', fg='white',
                             font=('Arial', 10), relief='flat',
                             command=msg_window.destroy)
        close_btn.pack(side='bottom', pady=(10, 0))
        
        # 开始倒计时
        update_countdown()
        
        # 设置自动关闭
        msg_window.after(delay_ms, msg_window.destroy)

    def configure_game(self, game):
        """配置游戏设置"""
        config_window = tk.Toplevel(self.root)
        config_window.title(f"配置 - {game['name']}")
        config_window.geometry("400x500")
        config_window.configure(bg='#1a1a1a')
        config_window.transient(self.root)
        config_window.grab_set()

        title_label = tk.Label(config_window, text=f"🎮 {game['name']} 设置",
                               bg='#1a1a1a', fg='#ffffff',
                               font=('Arial', 18, 'bold'))
        title_label.pack(pady=20)

        settings_frame = tk.Frame(config_window, bg='#2d2d2d', relief='flat')
        settings_frame.pack(fill='both', expand=True, padx=20, pady=10)

        setting_vars = {}
        for setting_key, setting_value in game['settings'].items():
            create_setting_widget(settings_frame, setting_key, setting_value, setting_vars)

        button_frame = tk.Frame(config_window, bg='#1a1a1a')
        button_frame.pack(fill='x', padx=20, pady=20)

        def save_settings():
            for key, var in setting_vars.items():
                if hasattr(var, 'get'):
                    game['settings'][key] = var.get()
            self.save_games_config()
            config_window.destroy()
            messagebox.showinfo("保存成功", "设置已保存！")

        tk.Button(button_frame, text="保存设置",
                  bg='#2ecc71', fg='white',
                  font=('Arial', 12, 'bold'),
                  relief='flat', command=save_settings).pack(side='left', padx=5)
        tk.Button(button_frame, text="取消",
                  bg='#e74c3c', fg='white',
                  font=('Arial', 12), relief='flat',
                  command=config_window.destroy).pack(side='right', padx=5)

    def show_game_details(self, game):
        """显示游戏详情"""
        detail_window = tk.Toplevel(self.root)
        detail_window.title(f"详情 - {game['name']}")
        detail_window.geometry("600x700")
        detail_window.configure(bg='#1a1a1a')
        detail_window.transient(self.root)
        detail_window.grab_set()

        # 图片显示
        image_frame = tk.Frame(detail_window, bg='#2d2d2d')
        image_frame.pack(fill='x', padx=20, pady=20)

        # 加载游戏图片
        image_path = game.get('image', '')
        if image_path and os.path.exists(image_path):
            try:
                image = Image.open(image_path)
                image = image.resize((400, 267), Image.LANCZOS)
                game_image = ImageTk.PhotoImage(image)
                image_label = tk.Label(image_frame, image=game_image, bg='#2d2d2d')
                image_label.image = game_image
                image_label.pack()
            except Exception as e:
                # 显示游戏图标
                icon_label = tk.Label(image_frame, text=get_game_icon(game['id']),
                                      bg='#2d2d2d', fg='#007bff',
                                      font=('Microsoft YaHei UI', 72))
                icon_label.pack(pady=40)
                print(f"加载详情图片失败: {e}")
        else:
            # 显示游戏图标
            icon_label = tk.Label(image_frame, text=get_game_icon(game['id']),
                                  bg='#2d2d2d', fg='#007bff',
                                  font=('Microsoft YaHei UI', 72))
            icon_label.pack(pady=40)

        text_widget = tk.Text(detail_window, bg='#2d2d2d', fg='#ffffff',
                              font=('Arial', 11), wrap='word', height=15)
        scrollbar = tk.Scrollbar(detail_window, orient='vertical', command=text_widget.yview)
        text_widget.configure(yscrollcommand=scrollbar.set)

        # 检查游戏文件是否存在
        game_path = get_game_path(game['path'])
        file_exists = os.path.exists(game_path)
        file_status = "✅ 已找到" if file_exists else "❌ 未找到"

        # 格式化最后游玩时间
        last_played = game.get('last_played', '从未游玩')
        if last_played and last_played != '从未游玩':
            try:
                # 尝试解析ISO格式日期并格式化
                dt = datetime.fromisoformat(last_played)
                last_played = dt.strftime('%Y-%m-%d %H:%M:%S')
            except:
                # 如果解析失败，保持原样
                pass

        details = f"""
🎮 游戏名称: {game['name']}
📂 类别: {game['category']}
⭐ 评分: {game['rating']}/5.0
🎯 游玩次数: {game['play_count']}
📅 最后游玩: {last_played}
📁 文件路径: {game_path} ({file_status})
🔧 状态: {status_text.get(game['status'], '未知')}

📖 游戏描述:
{game['description']}

⚙️ 当前设置:
"""
        for key, value in game['settings'].items():
            if isinstance(value, bool):
                value_str = "✅ 是" if value else "❌ 否"
                details += f"• {key.replace('_', ' ').title()}: {value_str}\n"
            else:
                details += f"• {key.replace('_', ' ').title()}: {value}\n"

        text_widget.insert('1.0', details)
        text_widget.configure(state='disabled')

        text_widget.pack(side='left', fill='both', expand=True, padx=20, pady=(0, 20))
        scrollbar.pack(side='right', fill='y', pady=(0, 20))
        
        # 添加按钮区域
        button_frame = tk.Frame(detail_window, bg='#1a1a1a')
        button_frame.pack(fill='x', padx=20, pady=(0, 20))
        
        if file_exists and game['status'] == 'available':
            play_btn = tk.Button(button_frame, text="▶ 开始游戏",
                              bg='#2ecc71', fg='white',
                              font=('Arial', 12, 'bold'),
                              relief='flat',
                              command=lambda: [self.start_game(game), detail_window.destroy()])
            play_btn.pack(side='left', padx=(0, 10))
        
        close_btn = tk.Button(button_frame, text="关闭",
                           bg='#e74c3c', fg='white',
                           font=('Arial', 12),
                           relief='flat',
                           command=detail_window.destroy)
        close_btn.pack(side='right')

    def add_game(self):
        """添加新游戏"""
        add_window = tk.Toplevel(self.root)
        add_window.title("添加游戏")
        add_window.geometry("500x500")
        add_window.configure(bg='#1a1a1a')
        add_window.transient(self.root)
        add_window.grab_set()

        fields = {}

        # 创建滚动区域
        main_frame = tk.Frame(add_window, bg='#1a1a1a')
        main_frame.pack(fill='both', expand=True, padx=20, pady=20)
        
        canvas = tk.Canvas(main_frame, bg='#1a1a1a', highlightthickness=0)
        scrollbar = ttk.Scrollbar(main_frame, orient="vertical", command=canvas.yview)
        scrollable_frame = tk.Frame(canvas, bg='#1a1a1a')
        
        scrollable_frame.bind(
            "<Configure>",
            lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
        )
        
        canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
        canvas.configure(yscrollcommand=scrollbar.set)
        
        canvas.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")

        # 标题
        title_label = tk.Label(scrollable_frame, text="添加新游戏",
                              bg='#1a1a1a', fg='#ffffff',
                              font=('Microsoft YaHei UI', 18, 'bold'))
        title_label.pack(anchor='w', pady=(0, 15))

        # 基本信息
        tk.Label(scrollable_frame, text="基本信息", 
                bg='#1a1a1a', fg='#3498db',
                font=('Microsoft YaHei UI', 14)).pack(anchor='w', pady=(5, 10))
        
        # 游戏名称
        tk.Label(scrollable_frame, text="游戏名称:", bg='#1a1a1a', fg='#ffffff',
                font=('Microsoft YaHei UI', 11)).pack(anchor='w', pady=(5, 2))
        fields['name'] = tk.Entry(scrollable_frame, bg='#3d3d3d', fg='#ffffff', 
                                 insertbackground='#ffffff', font=('Microsoft YaHei UI', 11))
        fields['name'].pack(fill='x', pady=(0, 10))

        # 游戏描述
        tk.Label(scrollable_frame, text="游戏描述:", bg='#1a1a1a', fg='#ffffff',
                font=('Microsoft YaHei UI', 11)).pack(anchor='w', pady=(5, 2))
        fields['description'] = tk.Text(scrollable_frame, bg='#3d3d3d', fg='#ffffff', 
                                      insertbackground='#ffffff', font=('Microsoft YaHei UI', 11),
                                      height=3)
        fields['description'].pack(fill='x', pady=(0, 10))

        # 文件路径
        tk.Label(scrollable_frame, text="游戏文件:", bg='#1a1a1a', fg='#ffffff',
                font=('Microsoft YaHei UI', 11)).pack(anchor='w', pady=(5, 2))
        path_frame = tk.Frame(scrollable_frame, bg='#1a1a1a')
        path_frame.pack(fill='x', pady=(0, 10))

        fields['path'] = tk.Entry(path_frame, bg='#3d3d3d', fg='#ffffff', 
                                 insertbackground='#ffffff', font=('Microsoft YaHei UI', 11))
        fields['path'].pack(side='left', fill='x', expand=True)

        def browse_file():
            filename = filedialog.askopenfilename(
                title="选择游戏文件",
                filetypes=[("Python文件", "*.py"), ("可执行文件", "*.exe"), ("所有文件", "*.*")]
            )
            if filename:
                fields['path'].delete(0, tk.END)
                fields['path'].insert(0, filename)

        tk.Button(path_frame, text="浏览", bg='#1565c0', fg='white', 
                 relief='flat', font=('Microsoft YaHei UI', 10),
                 command=browse_file).pack(side='right', padx=5)

        # 图片路径
        tk.Label(scrollable_frame, text="游戏图片:", bg='#1a1a1a', fg='#ffffff',
                font=('Microsoft YaHei UI', 11)).pack(anchor='w', pady=(5, 2))
        image_frame = tk.Frame(scrollable_frame, bg='#1a1a1a')
        image_frame.pack(fill='x', pady=(0, 10))

        fields['image'] = tk.Entry(image_frame, bg='#3d3d3d', fg='#ffffff', 
                                  insertbackground='#ffffff', font=('Microsoft YaHei UI', 11))
        fields['image'].pack(side='left', fill='x', expand=True)

        def browse_image():
            filename = filedialog.askopenfilename(
                title="选择游戏图片",
                filetypes=[("图片文件", "*.png *.jpg *.jpeg *.gif"), ("所有文件", "*.*")]
            )
            if filename:
                fields['image'].delete(0, tk.END)
                fields['image'].insert(0, filename)

        tk.Button(image_frame, text="浏览", bg='#1565c0', fg='white', 
                 relief='flat', font=('Microsoft YaHei UI', 10),
                 command=browse_image).pack(side='right', padx=5)

        # 其他信息
        tk.Label(scrollable_frame, text="其他信息", 
                bg='#1a1a1a', fg='#3498db',
                font=('Microsoft YaHei UI', 14)).pack(anchor='w', pady=(15, 10))
                
        # 类别
        tk.Label(scrollable_frame, text="游戏类别:", bg='#1a1a1a', fg='#ffffff',
                font=('Microsoft YaHei UI', 11)).pack(anchor='w', pady=(5, 2))
        fields['category'] = ttk.Combobox(scrollable_frame, values=['益智', '动作', '冒险', '策略', '射击', '休闲', '其他'],
                                         font=('Microsoft YaHei UI', 11))
        fields['category'].pack(fill='x', pady=(0, 10))
        fields['category'].set('益智')
        
        # 评分
        tk.Label(scrollable_frame, text="初始评分 (0-5):", bg='#1a1a1a', fg='#ffffff',
                font=('Microsoft YaHei UI', 11)).pack(anchor='w', pady=(5, 2))
        fields['rating'] = ttk.Spinbox(scrollable_frame, from_=0, to=5, increment=0.1,
                                      font=('Microsoft YaHei UI', 11))
        fields['rating'].pack(fill='x', pady=(0, 10))
        fields['rating'].set('4.0')

        # 按钮区域
        button_frame = tk.Frame(add_window, bg='#1a1a1a')
        button_frame.pack(fill='x', padx=20, pady=(0, 20))

        def save_game():
            name = fields['name'].get().strip()
            description = fields['description'].get('1.0', 'end-1c').strip()
            path = fields['path'].get().strip()
            category = fields['category'].get()
            image = fields['image'].get().strip()
            
            try:
                rating = float(fields['rating'].get())
                if rating < 0: rating = 0
                if rating > 5: rating = 5
            except:
                rating = 4.0

            if not name or not path:
                messagebox.showerror("错误", "请填写游戏名称和文件路径！")
                return

            # 生成唯一ID
            game_id = name.lower().replace(' ', '_')
            counter = 1
            while any(g['id'] == game_id for g in self.games_data):
                game_id = f"{name.lower().replace(' ', '_')}_{counter}"
                counter += 1

            new_game = {
                "id": game_id,
                "name": name,
                "description": description,
                "path": path,
                "category": category,
                "rating": rating,
                "play_count": 0,
                "last_played": None,
                "image": image,
                "settings": {
                    "difficulty": "normal",
                    "sound": True
                },
                "status": "available"
            }

            self.games_data.append(new_game)
            self.save_games_config()
            self.refresh_games_list()
            add_window.destroy()
            messagebox.showinfo("成功", "游戏已添加！")

        tk.Button(button_frame, text="保存", bg='#2ecc71', fg='white',
                  font=('Microsoft YaHei UI', 12, 'bold'), relief='flat', 
                  command=save_game).pack(side='left', padx=(0, 10))
        tk.Button(button_frame, text="取消", bg='#e74c3c', fg='white',
                  font=('Microsoft YaHei UI', 12), relief='flat', 
                  command=add_window.destroy).pack(side='right')

    def show_statistics(self):
        """显示游戏统计"""
        stats_window = tk.Toplevel(self.root)
        stats_window.title("游戏统计")
        stats_window.geometry("400x300")
        stats_window.configure(bg='#1a1a1a')
        stats_window.transient(self.root)
        stats_window.grab_set()

        total_games = len(self.games_data)
        available_games = len([g for g in self.games_data if g['status'] == 'available'])
        total_plays = sum(g['play_count'] for g in self.games_data)

        stats_text = f"""
📊 游戏统计信息

🎮 总游戏数: {total_games}
✅ 可用游戏: {available_games}
🎯 总游玩次数: {total_plays}
📅 统计时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

📈 最受欢迎游戏:
"""
        most_played = max(self.games_data, key=lambda x: x['play_count'], default=None)
        if most_played and most_played['play_count'] > 0:
            stats_text += f"{most_played['name']} ({most_played['play_count']} 次)"

        text_widget = tk.Text(stats_window, bg='#2d2d2d', fg='#ffffff',
                              font=('Arial', 11), wrap='word', height=10)
        text_widget.insert('1.0', stats_text)
        text_widget.configure(state='disabled')
        text_widget.pack(fill='both', expand=True, padx=20, pady=20)


    def on_closing(self):
        """处理窗口关闭"""
        self.save_games_config()
        self.executor.shutdown(wait=False)  # 关闭线程池
        self.root.destroy()


if __name__ == "__main__":
    root = tk.Tk()
    app = GameCollectionApp(root)
    root.mainloop()
